<template>
    <div>
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="原坐标系">
                <el-select placeholder="请选择原坐标系" v-model="coordstartType" style="width: 180px">
                    <el-option v-for="(item, ind) in coordTypeArr" :key="ind" :label="item.name"
                        :value="item.val"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="坐标">
                <el-input style="width: 300px;margin: 0 10px;" placeholder="请输入坐标用逗号分割" v-model="lnglat" />
            </el-form-item>
            <el-form-item v-if="coordstartType == 'cgcs2000'" label="三度分带号">
                <el-select placeholder="请选择三度分带号" v-model="cgcsdh" style="width: 180px">
                    <el-option v-for="(item, ind) in cgcsArr" :key="ind" :label="item.name" :value="item.val"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="目标坐标系">
                <el-select placeholder="请选择目标坐标系" v-model="coordlastType" style="width: 180px">
                    <el-option v-for="(item, ind) in coordTypeArr" :key="ind" :label="item.name"
                        :value="item.val"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="startConvert">转换</el-button>
            </el-form-item>
        </el-form>
        <div>
            <div>转换结果：</div>

            <table class="tab" border="1px">
                <tr>
                    <td>{{ coordstartType }}</td>
                    <td width="350">{{ lnglat }}</td>
                </tr>
                <tr>
                    <td>{{ coordlastType }}</td>
                    <td>{{ resultlnglat }}</td>
                </tr>
            </table>
        </div>

        <input type="file" @change="handleUpload" accept=".xlsx, .xls" />
        <button @click="conversionAll">转换并导出</button>
    </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { coordConvert } from "./coord"
export default {
    mixins: [coordConvert],
    data() {
        return {
            coordstartType: "wgs84",
            coordlastType: "wgs84",
            coordTypeArr: [
                { name: 'wgs84', val: 'wgs84' },
                { name: 'gcj02', val: 'gcj02' },
                { name: 'cgcs2000', val: 'cgcs2000' },
            ],
            lnglat: "",//输入坐标
            resultlnglat: '',//结果
            cgcsdh: "75", //三分度带号
            cgcsArr: [], // 3度分带号
        };
    },
    mounted() {
        let dh = []
        Array.from({ length: 21 }, (_, ind) => {
            const zoneNumber = 25 + ind;
            const longitude = 75 + ind * 3;

            // 创建对象并推送到数组中
            const obj = {
                name: `3度分带号${zoneNumber} - ${longitude}E`,
                val: longitude + ''
            };
            dh.push(obj)
        })
        this.cgcsArr = dh
    },
    methods: {
        startConvert() {
            if (!this.lnglat)  this.$message.error('请输入坐标')
            // 使用正则表达式匹配中文逗号或英文逗号，并拆分字符串
            let lnglat = this.lnglat.split(/[,，]/);
            lnglat[0] = Number(lnglat[0])
            lnglat[1] = Number(lnglat[1])
            switch (this.coordstartType) {
                case 'wgs84':
                    switch (this.coordlastType) {
                        case "wgs84":
                            this.resultlnglat = this.lnglat
                            break;
                        case "gcj02":
                            this.resultlnglat = this.wgs84ToGcj02(lnglat[0], lnglat[1]).join(',')
                            break;
                        case "cgcs2000":
                            this.resultlnglat = this.wgs84ToCgcs2000(lnglat[0], lnglat[1]).join(',')
                            break;
                        default:
                            break;
                    }
                    break;
                case 'gcj02':
                    this.gcjVal = this.lnglat
                    switch (this.coordlastType) {
                        case "wgs84":
                            this.resultlnglat = this.Gcj02ToWgs84(lnglat[0], lnglat[1])
                            break;
                        case "gcj02":
                            this.resultlnglat = this.lnglat
                            break;
                        case "cgcs2000":
                            let wgsTemp = this.Gcj02ToWgs84(lnglat[0], lnglat[1])
                            this.resultlnglat = this.wgs84ToCgcs2000(wgsTemp[0], wgsTemp[1]).join(',')
                            break;
                        default:
                            break;
                    }
                    break;
                case 'cgcs2000':
                    switch (this.coordlastType) {
                        case "wgs84":
                            this.resultlnglat = this.Cgcs2000ToWgs84(lnglat[0], lnglat[1], this.cgcsdh).join(',')
                            break;
                        case "gcj02":
                            let wgs84Temp = this.Cgcs2000ToWgs84(lnglat[0], lnglat[1], this.cgcsdh)
                            this.resultlnglat = this.wgs84ToGcj02(wgs84Temp[0], wgs84Temp[1]).join(',')
                            break;
                        case "cgcs2000":
                            let ind = this.cgcsArr.findIndex(s => s.val == this.cgcsdh)
                            this.resultlnglat = this.lnglat + ',' + (ind + 25)
                            break;
                        default:
                            break;
                    }
                    break;

                default:
                    break;
            }
        },
        handleUpload() {
            let _this = this
            const file = event.target.files[0];

            if (file) {
                const reader = new FileReader();

                reader.onload = (e) => {
                    const data = e.target.result;
                    const workbook = XLSX.read(data, { type: 'binary' });

                    // Assuming the data is in the first sheet
                    const sheetName = workbook.SheetNames[0];
                    const sheet = workbook.Sheets[sheetName];

                    // Convert sheet to array of objects
                    const dataArray = XLSX.utils.sheet_to_json(sheet, { header: 1 });
                    // console.log("dataArray",dataArray);
                    let title = dataArray[0]
                    // Skip the header row and convert the rest to the desired format
                    _this.parsedData = dataArray.slice(1).map(row => {
                        return {
                            // [`${title[0]}`]: row[0].toString(),
                            // [`${title[1]}`]: row[1].toString(),
                            "lng/X": Number(row[0]),
                            "lat/Y": Number(row[1]),
                        };
                    });
                    // console.log("_this.parsedData", _this.parsedData);
                };

                reader.readAsBinaryString(file);
            }
        },
        // 批量转换
        conversionAll() {
            // this.allTitle = ["lng/X", "lat/Y", "wgs84lng", "wgs84lat", "gcj02lng", "gcj02lat", "cgcs2000X", "cgcs2000Y"]
            switch (this.coordstartType) {
                case 'wgs84':
                    this.parsedData.forEach(sour => {
                        switch (this.coordlastType) {
                            case "wgs84":
                                sour.wgs84lng = sour['lng/X'].toString()
                                sour.wgs84lat = sour['lat/Y'].toString()
                                break;
                            case "gcj02":
                                let gcjVal = this.wgs84ToGcj02(sour['lng/X'], sour['lat/Y'])
                                sour.gcj02lng = gcjVal[0].toString()
                                sour.gcj02lat = gcjVal[1].toString()
                                break;
                            case "cgcs2000":
                                let CGCSVal = this.wgs84ToCgcs2000(sour['lng/X'], sour['lat/Y'])
                                sour.cgcs2000X = CGCSVal[0].toString()
                                sour.cgcs2000Y = CGCSVal[1].toString()
                                break;
                            default:
                                break;
                        }
                    })
                    break;
                case 'gcj02':
                    this.parsedData.forEach(sour => {
                        switch (this.coordlastType) {
                            case "wgs84":
                                let wgsTemp = this.Gcj02ToWgs84(sour['lng/X'], sour['lat/Y'])
                                sour.wgs84lng = wgsTemp[0].toString()
                                sour.wgs84lat = wgsTemp[1].toString()
                                break;
                            case "gcj02":
                                sour.gcj02lng = sour['lng/X'].toString()
                                sour.gcj02lat = sour['lat/Y'].toString()
                                break;
                            case "cgcs2000":
                                let wgsTemp2000 = this.Gcj02ToWgs84(sour['lng/X'], sour['lat/Y'])
                                let CGCSVal = this.wgs84ToCgcs2000(wgsTemp2000[0], wgsTemp2000[1])
                                sour.cgcs2000X = CGCSVal[0].toString()
                                sour.cgcs2000Y = CGCSVal[1].toString()
                                break;
                            default:
                                break;
                        }
                    })
                    break;
                case 'cgcs2000':
                    this.parsedData.forEach(sour => {
                        switch (this.coordlastType) {
                            case "wgs84":
                                let wgs84Temp = this.Cgcs2000ToWgs84(sour['lng/X'], sour['lat/Y'], this.cgcsdh)
                                sour.wgs84lng = wgs84Temp[0].toString()
                                sour.wgs84lat = wgs84Temp[1].toString()
                                break;
                            case "gcj02":
                                let wgs84TempGcj = this.Cgcs2000ToWgs84(sour['lng/X'], sour['lat/Y'], this.cgcsdh)
                                let gcjVal = this.wgs84ToGcj02(wgs84TempGcj[0], wgs84TempGcj[1])
                                sour.gcj02lng = gcjVal[0].toString()
                                sour.gcj02lat = gcjVal[1].toString()
                                break;
                            case "cgcs2000":
                                sour.cgcs2000X = sour['lng/X'].toString()
                                sour.cgcs2000Y = sour['lat/Y'].toString()
                                break;
                            default:
                                break;
                        }
                    })
                    break;

                default:
                    break;
            }
            this.modifyAndExport()
        },
        // 导出
        modifyAndExport() {
            // Create a new worksheet
            const ws = XLSX.utils.json_to_sheet(this.parsedData);

            // Add header row
            // XLSX.utils.sheet_add_aoa(ws, [this.allTitle], { origin: -1 });

            // Create a new workbook and add the worksheet
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // Export the workbook to an Excel file
            XLSX.writeFile(wb, '转换后坐标数据.xlsx');
        }
    },
}
</script>
<style scoped>
.tab {
    width: 100%;
    max-width: 500px;
    margin-top: 10px;
}

.tab tr {
    line-height: 40px;
}
</style>